import type { ProColumns } from '@ant-design/pro-components';
import {
  EditableProTable,
  ProCard,
  ProFormField,
} from '@ant-design/pro-components';
import { Button,Modal,Form,Input,message } from 'antd';
import React, { useEffect, useState } from 'react';

type DataSourceType = {
  id: React.Key;
  name?: string;
  displayName?: string;
  description?: string;
  valType?: string;
  entityType?: string;
  length?: string;
  formula?: string;
  validation?: string;
  created_at?: number;
  refEntityId?: string;
  refTableName?: string;
  defaultValue?: string;
  isRequired?: string;
  //children?: DataSourceType[];
};



//nodeInfo是表名name
export default (nodeInfo) => {


 
  let userId = 1;

 let entityName = nodeInfo.nodeInfo;

  const defaultData: DataSourceType[] = 
  [{
    id: React.Key,
    name: "id",
    displayName: "主键",
    valType: "int",
    entityType: "NORMAL",
    refEntityId: "",
    refTableName: "",
    length: "",
    validation: "",
    formula: "",
    defaultValue: "",
    isRequired: "true",
    description: ""
  
  },]
     
    
 
  useEffect(()=>{
    //console.log('change');
    fetch('http://localhost:8080/api/v1/field/lc?entityName=' + entityName)
    .then(response => response.json())
    .then(data => {
      console.log(data.data); 
      
      setDataSource(data.data);
    });
    //setDataSource(defaultData);
    
  },[nodeInfo]);

  function convertToFullType(sourceArray){
    return sourceArray.map( source => {
       return {
      ...source,
      refEntityId: "",
      refTableName: "",
      validation: "",
      formula: "",
      defaultValue: "",
      isRequired: "true",
    }
    })
   
  }
  
  const[isModalOpen, setIsModalOpen] = useState(false);
  const [appForm] = Form.useForm();
  
  console.log("nodeInfo",nodeInfo);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>(
    () => defaultData,
  );

  const [messageApi, contextHolder] = message.useMessage();

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      width: '10%',
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          }
          
        ],
      },
    },
    {
        title: '中文名称',
        dataIndex: 'displayName',
        width: '10%',
      },
      {
        title: '长度',
        dataIndex: 'length',
        width: '10%',
      },
    {
      title: '数据类型',
      width: '10%',
      key: 'valType',
      dataIndex: 'valType',
      valueType: 'select',
      valueEnum: {
        int: { text: '整数',  },
        varchar: {
          text: '字符串',
          
        },
        text: {
          text: '文本',
          
        },
        float:{
            text: '浮点数'
        }
      },
    },
    {
        title: '实体类型',
        width: '10%',
        key: 'entityType',
        dataIndex: 'entityType',
        valueEnum: {
            NORMAL: {text: "普通"},
            REFERENCE: {text: "引用"}
        }

    },
    {
      title: '描述',
      width: '10%',
      dataIndex: 'description',
    },
    {
      title: '操作',
      width: '10%',
      valueType: 'option',
      
      render: () => {
        return null;
      },
    },
  ];

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    fetch('http://localhost:8080/api/v1/app',{
      method: 'POST', 
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(
        {
          name: appForm.getFieldValue('name'),
          displayName: appForm.getFieldValue('displayName')
        }
      )
  }).then(response => response.json())
  .then(data => {
    console.log(data);
    
    localStorage.setItem('appId',data.data);
    
  })
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <>
    {contextHolder}
      <EditableProTable<DataSourceType>
        headerTitle={entityName}
        columns={columns}
        rowKey="id"
        scroll={{
          x: 960,
        }}
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          //FIXME: id可能重复但概率不大
          record: () => ({
            id: `${Math.floor(Date.now() / 100000000)}${Math.floor(Math.random() * 1000)}`,
          }),
        }}
        toolBarRender={() => {
          return [
            <>
            <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
              
              <Form form={appForm}>
                <Form.Item label="应用名称" name="name">
                  <Input placeholder='请输入应用名称'/>
                </Form.Item>
                <Form.Item label="中文名称" name="displayName">
                  <Input placeholder='请输入中文名称'/>
                </Form.Item>
              </Form>
            </Modal>
            <Button onClick={showModal}>
              创建项目
            </Button>
            <Button
              type="primary"
              key="save"
              onClick={() => {
                // dataSource 就是当前数据，可以调用 api 将其保存
                fetch('http://localhost:8080/api/v1/field?entityName='+entityName+'&userId='+userId,{
                  method: 'POST', 
                  headers: {
                      'Content-Type': 'application/json'
                  },
                  body: JSON.stringify(
                    convertToFullType(dataSource)
                  )
              }).then(response => response.json())
              .then(data => {console.log(data)})
               console.log(convertToFullType(dataSource));
               messageApi.open({
                type: 'success',
                content: '保存成功',
              });
              }}
            >
              保存数据
            </Button>,
            </>
          ];
        }}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete];
          },
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          onChange: setEditableRowKeys,
        }}
      />
      {/* <ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
        <ProFormField
          ignoreFormItem
          fieldProps={{
            style: {
              width: '100%',
            },
          }}
          mode="read"
          valueType="jsonCode"
          text={JSON.stringify(dataSource)}
        />
      </ProCard> */}
    </>
  );
};